<p>Mutable objects are those whose state can be changed. For instance, an array is mutable, but a String is not. Mutable class members should never be
returned to a caller or accepted and stored directly. Doing so leaves you vulnerable to unexpected changes in your class state.</p>
<p>Instead use an unmodifiable <code>Collection</code> (via <code>Collections.unmodifiableCollection</code>,
<code>Collections.unmodifiableList</code>, …​) or make a copy of the mutable object, and store or return the copy instead.</p>
<p>This rule checks that arrays, collections and Dates are not stored or returned directly.</p>
<h2>Noncompliant Code Example</h2>
<pre>
class A {
  private String [] strings;

  public A () {
    strings = new String[]{"first", "second"};
  }

  public String [] getStrings() {
    return strings; // Noncompliant
  }

  public void setStrings(String [] strings) {
    this.strings = strings;  // Noncompliant
  }
}

public class B {

  private A a = new A();  // At this point a.strings = {"first", "second"};

  public void wreakHavoc() {
    a.getStrings()[0] = "yellow";  // a.strings = {"yellow", "second"};
  }
}
</pre>
<h2>Compliant Solution</h2>
<pre>
class A {
  private String [] strings;

  public A () {
    strings = new String[]{"first", "second"};
  }

  public String [] getStrings() {
    return strings.clone();
  }

  public void setStrings(String [] strings) {
    this.strings = strings.clone();
  }
}

public class B {

  private A a = new A();  // At this point a.strings = {"first", "second"};

  public void wreakHavoc() {
    a.getStrings()[0] = "yellow";  // a.strings = {"first", "second"};
  }
}
</pre>
<h2>See</h2>
<ul>
  <li> <a href="https://cwe.mitre.org/data/definitions/374.html">MITRE, CWE-374</a> - Passing Mutable Objects to an Untrusted Method </li>
  <li> <a href="https://cwe.mitre.org/data/definitions/375.html">MITRE, CWE-375</a> - Returning a Mutable Object to an Untrusted Caller </li>
  <li> <a href="https://wiki.sei.cmu.edu/confluence/x/OTdGBQ">CERT, OBJ05-J.</a> - Do not return references to private mutable class members </li>
  <li> <a href="https://wiki.sei.cmu.edu/confluence/x/HTdGBQ">CERT, OBJ06-J.</a> - Defensively copy mutable inputs and mutable internal components
  </li>
  <li> <a href="https://wiki.sei.cmu.edu/confluence/x/VzZGBQ">CERT, OBJ13-J.</a> - Ensure that references to mutable objects are not exposed </li>
</ul>

